package com.googlecode.contests_repo.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.contests_repo.cmd.tools.ContestRepoValidator;
import com.googlecode.contests_repo.core.WebTools;
import com.googlecode.contests_repo.core.WebTools.ResourceType;
import com.googlecode.contests_repo.core.config.ConfigurationManager;
import com.googlecode.contests_repo.core.model.ResourcesUtils;
import com.googlecode.contests_repo.validation.ResourceValidator;

/**
 * Servlet implementation class ValidateResourceServlet
 */
@WebServlet("/ValidateResourceServlet")
public class ValidateResourceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// get resource type
		String path = request.getParameter("path");
		ResourceType resourceType = WebTools.getResourceType(path);
		System.out.println("Resource type = " +  resourceType);
		if (resourceType == null) {
			return;
		}

		// validate
		ResourceValidator validator = ContestRepoValidator
				.createValidator(resourceType.getOptionString());
		String fullResourcePath = ResourcesUtils.getFullResourcePath(path);
		System.out.println(fullResourcePath);
		System.out.println("option: " + resourceType.getOptionString());
		List<String> errors = validator.validate(fullResourcePath);

		// change resource full paths to relative ones
		String repoRoot = ConfigurationManager.getInstance().getRepoRoot();
		for (int index = errors.size() - 1; index >= 0; index--) {
			String error = errors.get(index);
			if (error.contains(repoRoot)) {
				error = error.replace(repoRoot, "");
				errors.remove(index);
				errors.add(error);
			}
		}
		
		// send response
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(WebTools.buildErrorString(errors, "Resource is valid", true));
	}

}
